package com.gin.kotlin.gf2gamecommunity.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import coil3.imageLoader
import com.gin.kotlin.gf2gamecommunity.base.util.isWifiConnected
import com.gin.kotlin.gf2gamecommunity.base.util.preload
import com.gin.kotlin.gf2gamecommunity.navi.GF2Navigator
import com.gin.kotlin.gf2gamecommunity.routes.IndexRoute
import com.gin.kotlin.gf2gamecommunity.routes.accountManage
import com.gin.kotlin.gf2gamecommunity.routes.commentList
import com.gin.kotlin.gf2gamecommunity.routes.commentSingle
import com.gin.kotlin.gf2gamecommunity.routes.exchangeItem
import com.gin.kotlin.gf2gamecommunity.routes.gameInfo
import com.gin.kotlin.gf2gamecommunity.routes.heroineList
import com.gin.kotlin.gf2gamecommunity.routes.imagePreView
import com.gin.kotlin.gf2gamecommunity.routes.index
import com.gin.kotlin.gf2gamecommunity.routes.messageList
import com.gin.kotlin.gf2gamecommunity.routes.publish
import com.gin.kotlin.gf2gamecommunity.routes.reply
import com.gin.kotlin.gf2gamecommunity.routes.scoreLog
import com.gin.kotlin.gf2gamecommunity.routes.search
import com.gin.kotlin.gf2gamecommunity.routes.strategyList
import com.gin.kotlin.gf2gamecommunity.routes.themeDetail
import com.gin.kotlin.gf2gamecommunity.routes.themeList
import com.gin.kotlin.gf2gamecommunity.routes.topicList
import com.gin.kotlin.gf2gamecommunity.routes.userCenter
import com.gin.kotlin.gf2gamecommunity.routes.userRelatedList
import com.gin.kotlin.gf2gamecommunity.ui.theme.GF2GameCommunityTheme
import com.gin.kotlin.gf2gamecommunity.viewmodel.EmojiViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.MessageViewModel
import com.gin.kotlin.gf2gamecommunity.viewmodel.UserCenterViewModel
import kotlinx.coroutines.delay
import java.time.ZonedDateTime

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            GF2GameCommunityTheme {
                val navController = rememberNavController()
                // 提醒消息
                val messageViewModel = viewModel<MessageViewModel>()

                val navigator = GF2Navigator(navController)

                NavHost(
                    navController = navController,
                    startDestination = IndexRoute(),
                ) {

                    val onPopBackStack: () -> Unit = { navigator.onPopBackStack() }
                    fun <T : Any> nav(route: T) = navController.navigate(route)

                    // 首页路线
                    index(navigator = navigator, messageViewModel = messageViewModel)
                    // 主题列表路线
                    topicList(navigator = navigator, messageViewModel = messageViewModel)
                    // 回复列表路线
                    commentList(navigator = navigator, messageViewModel = messageViewModel)
                    // 图片预览
                    imagePreView()
                    // 账号管理
                    accountManage()
                    // 道具兑换
                    exchangeItem(navigator = navigator)
                    // 攻略列表
                    strategyList(onNavigateToCommentList = { nav(it) }, onPopBackStack = onPopBackStack)
                    // 话题中心
                    themeList(navigator = navigator)
                    // 单回复界面
                    commentSingle(navigator = navigator)
                    // 用户中心
                    userCenter(navigator = navigator)
                    // 游戏数据
                    gameInfo(onPopBackStack = onPopBackStack, onNavigateToHeroineList = { nav(it) })
                    // 展示人形修改
                    heroineList(onPopBackStack = onPopBackStack)
                    // 用户相关列表： 关注、粉丝
                    userRelatedList(onPopBackStack = onPopBackStack, onNavigateToUserCenter = { nav(it) })
                    // 积分记录
                    scoreLog(onPopBackStack = onPopBackStack)
                    // 提醒消息
                    messageList(navigator = navigator, messageViewModel = messageViewModel)
                    // 话题详情
                    themeDetail(navigator = navigator)
                    // 搜索： 主题 和 用户
                    search(navigator = navigator)

                    // 发布回复
                    reply(onPopBackStack = onPopBackStack)
                    // 发布主题
                    publish(onPopBackStack = onPopBackStack)
                }
            }

            AvatarPreLoad()
            EmojiPreLoad()
        }
    }
}

@Composable
fun DateTimeText(text: String) = Text("$text: ${ZonedDateTime.now().toLocalDateTime()}")


/**
 * Wifi下头像预载
 */
@Composable
private fun AvatarPreLoad(viewModel: UserCenterViewModel = viewModel()) {
    val context = LocalContext.current
    val tag = "AvatarPreLoad"
    LaunchedEffect(Unit) {
        val avatarInfoList = viewModel.avatarList.fetchAwait()?.takeIf { it.isNotEmpty() } ?: return@LaunchedEffect
        Log.i(tag, "头像预载开始，头像总数：${avatarInfoList.size} 个")

        // 预载请求，关闭内存缓存和解码步骤
        val urls = avatarInfoList.map { it.imgAddr }
        urls.forEach {
            while (!context.isWifiConnected()) {
                Log.i(tag, "当前非Wifi，等待10秒")
                delay(10000)
            }
            context.imageLoader.preload(it, context)
        }
        Log.i(tag, "头像预载完毕，头像总数：${avatarInfoList.size} 个")
    }
}

@Composable
private fun EmojiPreLoad(viewModel: EmojiViewModel = viewModel()) {
    val context = LocalContext.current
    val tag = "EmojiPreLoad"
    LaunchedEffect(Unit) {
        val emojiClassifies = viewModel.emojiList.fetchAwait()?.takeIf { it.isNotEmpty() } ?: return@LaunchedEffect

        // 预载请求
        val urls = emojiClassifies
            .flatMap { listOf(it.imgAddr, *it.emojiList.map { i -> i.urlPath }.toTypedArray()) }

        Log.i(tag, "表情预载开始，总数：${urls.size} 个")
        urls.forEach {
            while (!context.isWifiConnected()) {
                Log.i(tag, "当前非Wifi，等待10秒")
                delay(10000)
            }
            context.imageLoader.preload(it, context)
        }
        Log.i(tag, "表情预载完毕，总数：${urls.size} 个")
    }
}